#!/usr/bin/env bash

#######################################
# set variables below to create the config files, all files will create at ./config directory
#######################################

source ./env

##############################
# please do not modify anything below
##############################

for NODE in "${!MasterArray[@]}"; do
    echo "--- $NODE ${MasterArray[$NODE]} ---"
    mkdir -p config/$NODE/{keepalived,haproxy}
done

# create all kubeadm-config.yaml files

sed \
-e "s/KUBE_APISERVER/${VIP}:${API_PORT:=6443}/g" \
-e "s/KUBE_VERSION/${KUBE_VERSION}/g" \
-e "s/K8SHA_CIDR/${K8SHA_CIDR}/g" \
-e "s/K8SHA_SERVICE_SUBNET/${K8SHA_SERVICE_SUBNET}/g" \
kubeadm-config.yaml.tpl > kubeadm-config.yaml

for daemon in 10.96.0.1 127.0.0.1 kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster kubernetes.default.svc.cluster.local ${VIP} $(xargs -n1<<<${MasterArray[@]} | sort ); do
    sed -i "/apiServerCertSANs/a\- $daemon" kubeadm-config.yaml
done

echo "create kubeadm-config.yaml files success. kubeadm-config.yaml"

for NODE in "${!MasterArray[@]}"; do
    if [[ $NODE == 'k8s-m1' ]];then
        K8SHA_KA_PRIO=102
        K8SHA_KA_STATE=MASTER
    else
        K8SHA_KA_PRIO=100
        K8SHA_KA_STATE=BACKUP
    fi
    # haproxy
    sed '$r '<(paste <( seq -f'    server k8s-api-%g'  ${#MasterArray[@]} ) <( xargs -n1<<<${MasterArray[@]} | sort | sed 's#$#:6443  check#')) haproxy/haproxy.cfg.tpl > config/$NODE/haproxy/haproxy.cfg
    echo "create haproxy files success. config/$NODE/haproxy/"


    # keepalived
    sed \
    -e "s/K8SHA_KA_STATE/${K8SHA_KA_STATE}/g" \
    -e "s/K8SHA_KA_INTF/${INTERFACE}/g" \
    -e "s/K8SHA_IPLOCAL/${MasterArray[$NODE]} /g" \
    -e "s/K8SHA_KA_PRIO/${K8SHA_KA_PRIO}/g" \
    -e "s/K8SHA_VIP/${VIP}/g" \
    -e "s/K8SHA_KA_AUTH/${K8SHA_KEEPALIVED_AUTH}/g" keepalived/keepalived.conf.tpl > config/$NODE/keepalived/keepalived.conf
    

    # 修改keepalived(网卡和VIP写进去,使用下面命令)
    sed -ri "s#\{\{ interface \}\}#${interface}#" config/$NODE/keepalived/keepalived.conf 
    # unicast_peer 在网段不一致的时候,会出现 BACK 放无法访问 vip(本地 ip address 看不见 vip 地址)
    # sed -i '/unicast_peer/r '<(xargs -n1<<<${MasterArray[@]} | sort | sed 's#^#\t#') config/$NODE/keepalived/keepalived.conf

    echo "create keepalived files success. config/$NODE/keepalived/"

done
